import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import store from './store'
// NProgress.configure({ showSpinner: false })// NProgress Configuration

// permission judge function
// function hasPermission(roles, permissionRoles) {
//   if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
//   if (!permissionRoles) return true
//   return roles.some(role => permissionRoles.indexOf(role) >= 0)
// }

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // debugger
  if (getToken()) { // determine if there has token
    /* has token */
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.addRouters.length === 0) {
        store.dispatch('GetUserInfo').then(() => {
          store.dispatch('GenerateRoutes', { }).then(() => {
            next({ ...to, replace: true })
          })
        })
      } else {
        next()
        NProgress.done() 
      }
    }
  } else {
    if (to.path == '/login') { // 如果是登录页面路径，就直接next()
      next()
      NProgress.done()
    } else { // 不然就跳转到登录；
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
